package com.wan.controller.admin;

import com.alibaba.fastjson.JSON;
import com.wan.entity.Menu;
import com.wan.service.MenuService;
import com.wan.utils.MenuNode;
import com.wan.utils.TreeUtil;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/admin/menu")
public class MenuController {

    //注入MenuService
    @Resource
    private MenuService menuService;

    /**
     * 加载首页左侧菜单导航栏
     * @return
     */
    @RequestMapping(value = "/loadMenuList",produces = "text/html;charset=utf-8")
    public String loadMenuList(){
        //创建Map集合，保存菜单信息
        Map<String,Object> map = new LinkedHashMap<String, Object>();
        //创建Map集合，保存homeInfo信息
        Map<String,Object> homeInfo = new LinkedHashMap<String, Object>();
        //创建Map集合，保存logoInfo信息
        Map<String,Object> logoInfo = new LinkedHashMap<String, Object>();
        //调用查询所有菜单列表的方法
        List<Menu> menuList = menuService.findMenuList();
        //创建集合保存菜单关系
        List<MenuNode> menuNodeList = new ArrayList<MenuNode>();
        //循环遍历菜单列表，目的是创建菜单之间的层级关系
        for (Menu menu : menuList) {
            //创建菜单结点
            MenuNode menuNode = new MenuNode();
            menuNode.setHref(menu.getHref());
            menuNode.setIcon(menu.getIcon());
            menuNode.setId(menu.getId());
            menuNode.setPid(menu.getPid());
            menuNode.setSpread(menu.getSpread());
            menuNode.setTarget(menu.getTarget());
            menuNode.setTitle(menu.getTitle());
            //将对象添加到集合
            menuNodeList.add(menuNode);
        }

        //保存HomeInfo信息
        homeInfo.put("title","首页");
        homeInfo.put("href","/admin/desktop");

        //保存logoInfo信息
        logoInfo.put("title","竞赛管理系统");//logo标题
        logoInfo.put("image","/statics/layui/images/logo.png");//logo图片
        logoInfo.put("href","/admin/home.html");//首页地址

        //将菜单信息添加到MenuInfo集合中
        map.put("menuInfo", TreeUtil.toTree(menuNodeList,0));
        map.put("homeInfo",homeInfo);
        map.put("logoInfo",logoInfo);
        return JSON.toJSONString(map);
    }
}
